package com.gimi.cloud.bbp.merchantZone.consumer.service.product.impl;

import com.gimi.cloud.bbp.common.enums.ResponseCodeEnum;
import com.gimi.cloud.bbp.common.exception.MsgException;
import com.gimi.cloud.bbp.common.utils.CommonUtil;
import com.gimi.cloud.bbp.common.utils.EntityVerification;
import com.gimi.cloud.bbp.common.utils.JsonUtil;
import com.gimi.cloud.bbp.common.utils.StringUtil;
import com.gimi.cloud.bbp.common.utils.reqhead.Response;
import com.gimi.cloud.bbp.common.utils.reqhead.Util;
import com.gimi.cloud.bbp.dto.prod.EcProdCategoryDTO;
import com.gimi.cloud.bbp.dto.product.ProductDto;
import com.gimi.cloud.bbp.dto.product.ProductImgDTO;
import com.gimi.cloud.bbp.dto.product.ProductSkuDto;
import com.gimi.cloud.bbp.dto.product.ProductStatusDTO;
import com.gimi.cloud.bbp.dto.params.GetProductParams;
import com.gimi.cloud.bbp.merchantZone.consumer.feign.ProductFeignService;
import com.gimi.cloud.bbp.merchantZone.consumer.service.product.ProductService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;
import java.util.regex.Pattern;

@Service
public class ProductServiceImpl implements ProductService {
    private static Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);
    private final ProductFeignService productFeignService;

    @Autowired
    public ProductServiceImpl(ProductFeignService productFeignService) {
        this.productFeignService = productFeignService;
    }

    @Override
    public void releaseProduct(String requestData, HttpServletResponse response, HttpServletRequest request)
            throws MsgException {
        logger.info("srcData:" + requestData);
        EcProdCategoryDTO params = JsonUtil.jsonToBean(requestData,EcProdCategoryDTO.class);
        if (StringUtils.isNotEmpty(params.getProdCatId())) {
            Util.sendResponse(productFeignService.releaseProduct(params), response);
        } else {
            logger.error("参数错误");
            throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR);
        }

    }

    @Override
    public void getProduct(String requestData, HttpServletResponse response, HttpServletRequest request) throws MsgException {
        logger.info("srcData:" + requestData);
        GetProductParams params = JsonUtil.jsonToBean(requestData, GetProductParams.class);
        if (StringUtils.isNotEmpty(params.getProdId())) {
            Util.sendResponse(productFeignService.getProduct(params), response);
        } else {
            logger.error("参数错误");
            throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR);
        }
    }

    @Override
    public void updateProduct(String requestData, HttpServletResponse response, HttpServletRequest request)
            throws MsgException {
        logger.info("srcData:" + requestData);
        ProductDto pdto = JsonUtil.jsonToBean(requestData, ProductDto.class);
        if(pdto == null){
            throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR);
        }
        EntityVerification.checkByGroupsThrowsException(pdto, ProductDto.EditProduct.class);
        if(pdto.getProductSkuDto() == null || pdto.getProductSkuDto().size() < 1){
            throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR,"sku列表不能为空");
        }
        if(pdto.getProductImgEntity() == null || pdto.getProductImgEntity().size() < 1){
            throw new MsgException(ResponseCodeEnum.PROD_IMG_ERR,"商品图片不能为空");
        }
        List<ProductSkuDto> listSku = pdto.getProductSkuDto();
        for (ProductSkuDto dto : listSku) {
            boolean result = checkProdPrice(dto.getSkuPrice());
            if (!result) {
                throw new MsgException(ResponseCodeEnum.PROD_SKU_PRICE_ERR,"sku价格异常");
            }
        }
        pdto.setProdAdword(CommonUtil.checkParams(pdto.getProdAdword()));
//        pdto.setProdDesk(CommonUtil.checkParams(pdto.getProdDesk()));
        pdto.setProdKeywords(CommonUtil.checkParams(pdto.getProdKeywords()));
        pdto.setProdMeasureUnit(CommonUtil.checkParams(pdto.getProdMeasureUnit()));

        Util.sendResponse(productFeignService.updateProduct(pdto), response);
    }

    @Override
    public void addProduct(String requestData, HttpServletResponse response, HttpServletRequest request) throws MsgException {
        logger.info("srcData:" + requestData);
        ProductDto pdto = JsonUtil.jsonToBean(requestData, ProductDto.class);
        if (pdto == null) {
            throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR,"参数错误");
        }
        EntityVerification.checkByGroupsThrowsException(pdto, ProductDto.AddProduct.class);//校验一般参数
        if(StringUtil.isBlank(pdto.getProdName())){
            throw new MsgException(ResponseCodeEnum.PROD_SKU_PARAMS_ERR,"商品名称不能为空");
        }

        List<ProductSkuDto> listSku = pdto.getProductSkuDto();
        if(listSku == null || listSku.size() < 1){
            throw new MsgException(ResponseCodeEnum.PROD_SKU_PARAMS_ERR,"sku列表不能为空");
        }
        for (ProductSkuDto dto : listSku) {
            boolean result = checkProdPrice(dto.getSkuPrice());
            if (!result) {
                throw new MsgException(ResponseCodeEnum.PROD_SKU_PRICE_ERR,"商品Sku价格格式错误");
            }
        }
        List<ProductImgDTO> listProdImg = pdto.getProductImgEntity();
        if(listProdImg == null || listProdImg.size() < 1){
            throw new MsgException(ResponseCodeEnum.PROD_IMG_ERR,"商品图片列表不能为空");
        }
        pdto.setProdAdword(CommonUtil.checkParams(pdto.getProdAdword()));
        //pdto.setProdDesk(CommonUtil.checkParams(pdto.getProdDesk()));
        pdto.setProdKeywords(CommonUtil.checkParams(pdto.getProdKeywords()));
        pdto.setProdMeasureUnit(CommonUtil.checkParams(pdto.getProdMeasureUnit()));

        Util.sendResponse(productFeignService.addProduct(pdto), response);
    }

    @Override
    public void getStoreCats(String requestData, HttpServletResponse response, HttpServletRequest request)
            throws MsgException {
        logger.info("===>请求数据" + requestData);
        ProductDto params = JsonUtil.jsonToBean(requestData,ProductDto.class);
        /*String storeId = "1";
        String merchantId = "1";
        GetProdCatsParams params = new GetProdCatsParams();
        params.setMerchantId(merchantId);
        params.setStoreId(storeId);*/
        Util.sendResponse(productFeignService.getStoreCats(params), response);
    }

    @Override
    public void productList(String requestData, HttpServletResponse response, HttpServletRequest request) throws MsgException {
        logger.info("srcData:" + requestData);
        ProductDto params = JsonUtil.jsonToBean(requestData, ProductDto.class);
        EntityVerification.checkByGroupsThrowsException(params, ProductDto.productList.class);
        Util.sendResponse(productFeignService.getProductList(params), response);
    }

    @Override
    public void deleteProduct(String requestData, HttpServletResponse response, HttpServletRequest request) throws MsgException {
        logger.info("srcData:" + requestData);
        ProductStatusDTO params = JsonUtil.jsonToBean(requestData, ProductStatusDTO.class);
        if (StringUtil.isBlank(params.getReason())) {
            throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR, "删除原因不能为空");
        }else if(StringUtil.isBlank(params.getProdId())){
            throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR, "商品id不能为空");
        }
        Util.sendResponse(productFeignService.deleteProduct(params), response);
    }

    @Override
    public void upShelfProduct(String requestData, HttpServletResponse response, HttpServletRequest request) throws MsgException {
        logger.info("srcData:" + requestData);
        ProductStatusDTO params = JsonUtil.jsonToBean(requestData, ProductStatusDTO.class);
        if (params.getReason() == null || params.getProdId() == null) {
            throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR, "reason/prodId不能为空");
        }
        Util.sendResponse(productFeignService.upShelfProduct(params), response);
    }

    @Override
    public void offShelfProduct(String requestData, HttpServletResponse response, HttpServletRequest request) throws MsgException {
        logger.info("srcData:" + requestData);
        ProductStatusDTO params = JsonUtil.jsonToBean(requestData, ProductStatusDTO.class);
        if (params.getReason() == null || params.getProdId() == null) {
            throw new MsgException(ResponseCodeEnum.PARAMETER_ERROR, "reason/prodId不能为空");
        }
        Util.sendResponse(productFeignService.offShelfProduct(params), response);
    }

    @Override
    public void fileUpload(@RequestBody(required = false) String body, @RequestParam("file") MultipartFile file,
                           HttpServletResponse response, HttpServletRequest request) throws Exception {
        Response resp = new Response();
        if (file == null) {
            resp.setResponseCode(ResponseCodeEnum.UNKNOWN_ERROR, "请选择文件");
            Util.sendResponse(JsonUtil.toJson(resp), response);
            return;
        }
        Util.sendResponse(productFeignService.fileUpload(file), response);
    }

    //校验SKU价格
    private boolean checkProdPrice(BigDecimal skuPrice) {
        if (skuPrice != null) {
            Pattern pattern = Pattern.compile("^[0-9]+(.[0-9]{1,8})?$");
            String price = skuPrice.toString();
            if (pattern.matcher(price).matches()) {
                BigDecimal skuPrices = new BigDecimal(price.replace(" ", ""));
                if (skuPrices.compareTo(BigDecimal.ZERO) != 0) {
                    return true;
                }
            }
        }
        return false;
    }
}
